package org.zjx.app.service;

import com.alibaba.fastjson2.JSON;
import lombok.SneakyThrows;
import org.zjx.app.action.gather.GatherPetAction;
import org.zjx.app.action.gather.GatherPropAction;
import org.zjx.command.state.AccountState;
import org.zjx.command.state.ItemState;
import org.zjx.command.state.PetState;
import org.zjx.command.state.RoleState;
import org.zjx.window.action.Action;
import org.zjx.window.window.IWindow;

import java.io.File;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;

public class PetServiceAction extends Action {
    private static final String filePath = "pet_state.json";

    public PetServiceAction(IWindow targetWindow) {
        super(targetWindow);
    }

    @Override
    protected void doExecute() throws Exception {
        PetState petState = stateManager.getState(PetState.class);
        AccountState accountState = stateManager.getState(AccountState.class);
        String playerFilePath =  accountState.getPlayerId() + "-"+filePath;
        if (petState == null) {
            petState = getFilePath(new File(playerFilePath));
            if (petState == null) {
                targetWindow.submitAction(new GatherPetAction(targetWindow));
                return;
            }
        }
        saveData(playerFilePath,petState);
        stateManager.registerState(petState);
        stateManager.getGameState().setGatherPet(true);
    }

    @SneakyThrows
    public void saveData(String playerFilePath, PetState petState) {
        String json = JSON.toJSONString(petState);
        Files.write(Paths.get(playerFilePath), json.getBytes(StandardCharsets.UTF_8));
    }

    @SneakyThrows
    public PetState getFilePath(File file) {
        if (!file.exists()) return null;
        String json = new String(Files.readAllBytes(file.toPath()), StandardCharsets.UTF_8);
        if (json.isEmpty()) return null;
        return JSON.parseObject(json, PetState.class);
    }

}
